package com.jyhz.admin.service;

import com.jyhz.admin.utils.RandomGen;
import com.jyhz.admin.verifyCode.VerificationCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author: 谢君臣
 * @create: 2020-08-22 16:53
 * @founction: XXXX
 */
@Service
@Slf4j
public class MemberServiceImpl
{

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    SendMsgServiceImpl sendMsgServiceImpl;


    public Boolean generateCode(String telephone) {
        // 随机生成六位数验证码
        String code = RandomGen.codeGen();
        log.info("===>>> 验证码为:"+code);
        // 创建一个验证码对象
        VerificationCode codel = new VerificationCode(telephone,code,new Date().getTime());
        // 将验证码发送到手机用户
        Boolean bool = sendMsgServiceImpl.sendMsgService(codel);
        // String str = codel. //has散列
        // 将验证码对象放在缓存中
        redisTemplate.opsForValue().set(telephone,codel);
        return true;
    }

    public Boolean verifyCode(String telephone, String authCode) {
        VerificationCode vcode = (VerificationCode) redisTemplate.opsForValue().get(telephone);
        if (vcode!=null && authCode.equals(vcode.getCode()) && new Date().getTime()-vcode.getTimestamp()<= 1000*60*10)
        {
            Boolean delete = redisTemplate.delete(telephone);
            log.info("===>>> 清除验证码状态:"+delete);
            return true;
        }
        else
            return false;
    }
}
